package com.woodws.sys.security;

import com.woodws.sys.entity.SysLog;
import com.woodws.sys.service.SystemLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Web层日志切面
 *
 * @author 程序猿DD
 * @version 1.0.0
 * @date 16/5/17 上午10:42.
 * @blog http://blog.didispace.com
 */
@Aspect
@Order(5)
@Component
public class WebLogAspect {

    private static Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

    @Autowired
    private SystemLogService systemLogService;

    ThreadLocal<SysLog> log = new ThreadLocal<SysLog>();

    @Pointcut("execution(public * com.woodws.*.web..*.*(..))")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        SysLog log = new SysLog();
        log.setUrl(request.getRequestURL().toString());
        log.setHttpMethod(request.getMethod());
        log.setIp(request.getRemoteAddr());
        log.setClassMethod(joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.setStartTime(new Date());
        this.log.set(log);
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        SysLog log = this.log.get();
        if(ret != null){
            log.setResponse(ret.toString());
        }
        log.setEndTime(new Date());
        logger.info(log.toString());
        systemLogService.findByEndTimeIsNotNull();
        systemLogService.save(log);
    }


}

